package cn.smartopen.aispace.service.merchant;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.smartopen.aispace.base.BaseService;
import cn.smartopen.aispace.entity.TokenEntity;
import cn.smartopen.aispace.mapper.AppIdMapper;
import cn.smartopen.aispace.mapper.TokenMapper;
import cn.smartopen.aispace.utils.Utils;


@Service
public class ZeroSysService extends BaseService {

    @Autowired
    AppIdMapper appIdMapper;

    @Autowired
    TokenMapper tokenMapper;

    /**
     * 验证有效的APPID
     * 确认APPID和公钥信息一致
     * 保证调用的用户申请过该APPID
     * @param appId
     * @param publicKey
     * @return
     */
    public String validAppId(String appId, String publicKey) {
        var dto = appIdMapper.getAppIdAndServiceUserInfoByAppId(appId);

        if(dto==null){
            return "非法用户操作";
        }

        String pk = dto.getPublicKey();
        if(!(pk.equals(publicKey)||pk.equals(publicKey.substring(2)))){
            return "非法用户操作";
        }

        return "SUCCESS";
    }

    /**
     * 验证提交的用户令牌是正确的
     * 验证通过后系统会删除掉已经失效的令牌
     * @param tokenStr
     * @return
     */
    public String validToken(String tokenStr) {
        String msg = "";
        // 先找到令牌信息
        TokenEntity tokenEntity = tokenMapper.getTokenEntityByTokenStr(tokenStr);

        if(tokenEntity==null){
            msg = "无令牌信息";
        }else{
            Long nowTimeStamp = Utils.getCurrentTimeStamp();

            if(nowTimeStamp>tokenEntity.getExpireTimeStamp()){
                msg = "令牌过期";
            }else{
                msg = tokenEntity.getPublicKey();
            }
    
            // 删除令牌
            tokenMapper.deleteTokenEntityByPkId(tokenEntity.getPkId());
        }


        return msg;
    }
    
}
